package com.hebeu.xwl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hebeu.xwl.dao.AdminDao;
import com.hebeu.xwl.dao.AdminSaltDao;
import com.hebeu.xwl.pojo.Admin;
import com.hebeu.xwl.pojo.AdminSalt;
import com.hebeu.xwl.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminDao, Admin> implements AdminService {

    @Autowired
    AdminSaltDao adminSaltDao;

    @Override
    public Admin findByUsername(String username) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,username);
        Admin admin = baseMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public Admin findById(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public AdminSalt findAdminSalt(int id) {
        System.out.println("aaaa"+adminSaltDao);
        AdminSalt adminSalt = adminSaltDao.selectById(id);
        System.out.println(adminSalt);
        return  adminSalt;
    }

    @Override
    public void UpdatePassword(Admin admin) {
        UpdateWrapper<Admin> wrapper = new UpdateWrapper<>();
        wrapper.eq("username",admin.getUsername()).set("password",admin.getPassword());
        baseMapper.update(null,wrapper);
        return;
    }
    @Override
    public void UpdateStatus(Admin admin) {
        UpdateWrapper<Admin> wrapper = new UpdateWrapper<>();
        wrapper.eq("username",admin.getUsername()).set("status",admin.getStatus());
        baseMapper.update(null,wrapper);
        return;
    }

    @Override
    public int deleteById(int id) {
       return baseMapper.deleteById(id);
    }

    @Override
    public Boolean insertAdmin(Admin admin, String salt) {

        try {
            baseMapper.insert(admin);
            admin = this.findByUsername(admin.getUsername());
            admin.toString();
            AdminSalt adminSalt = new AdminSalt();
            adminSalt.setSalt(salt);
            adminSalt.setSaltid(admin.getId());
            adminSaltDao.insert(adminSalt);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional()
    public Boolean deleteAdmin(int id) {
         adminSaltDao.deleteById(id);
         return baseMapper.deleteById(id)==1;
    }
}
